<template>
    <myx-table
               :tableAttr="tableAttr"
               :search-field="'searchField'"
               :data="dataSource"
               :column="column"
               :showSelection="true"
               :showTableSearch="false"
               :showAddButton="false">
        <template #tableCell="{ scope }">
            <el-button type="primary" v-if="scope.column.key === 'action'"
                       @click="grantPermission(scope.row)">分配权限</el-button>
            <el-switch
                       :loading="switchLoading"
                       v-if="scope.column.key === 'rolestatus'"
                       size="large"
                       @change="changeStatus(scope.row)"
                       v-model="scope.row.status"
                       inline-prompt
                       style="--el-switch-on-color: #5598e9; --el-switch-off-color: #ff4949"
                       active-text="启用"
                       inactive-text="禁用"
                       active-value="1"
                       inactive-value="0" />
        </template>
    </myx-table>
    <myx-drawer
                :opened-fn="handleDrawerOpen"
                :show="showDrawer"
                @drawer-close="handleDrawerClose">
        <template v-slot:customButton>
            <el-button type="danger" @click="savePermission">保存</el-button>
        </template>
        <template #nested>
            <el-tree
                     v-loading="treeLoading"
                     element-loading-text="拼命加载中..."
                     element-loading-spinner="el-icon-loading"
                     element-loading-background="rgba(0, 0, 0, 0.3)"
                     check-on-click-node
                     empty-text="没有数据"
                     ref="tree"
                     default-expand-all
                     :check-strictly="true"
                     node-key="id"
                     :props="{ label: 'desc', disabled: 'disabled' }"
                     :data="treeData"
                     show-checkbox />
        </template>
    </myx-drawer>
</template>
<script setup name="role">
import myxDrawer from "components/ui-components/myx-drawer/index.vue"
import myxTable from "components/ui-components/myx-table/index.vue"
import * as api from "@/api/role"
import { onMounted, triggerRef } from "vue";
import useUser from "@/store/users"
let userStore = useUser()
//声明数据,展示表格
let dataSource = ref([])
let column = [
    {
        key: 'roleid',
        label: '角色ID',
        dataIndex: 'roleid'
    },
    {
        key: 'rolename',
        label: '角色名称',
        dataIndex: 'roleName',

    },
    {
        key: 'roledesc',
        label: '角色描述',
        dataIndex: 'desc'
    },
    {
        key: 'rolestatus',
        label: '角色状态',
        dataIndex: 'status',
        tableCell: true
    },
    {
        key: 'action',
        label: '操作',
        tableCell: true
    }
]
let loading = ref(false)

//表格透传的属性

let tableAttr = {
    defaultExpandAll: true,
    cellStyle: { textAlign: 'center' },
    headerCellStyle: { textAlign: 'center' },
    border: true
}

//获取角色列表的方法

let getAllRole = async () => {
    loading.value = true
    try {
        let res = await api.getAllRoleApi()
        // console.log(res)
        dataSource.value = res.data;
        loading.value = false;
    } catch (e) { }
}

//--------授权模块-----------
let tree = ref(null)
//声明响应式变量控制抽屉的显示与隐藏
let showDrawer = ref(false)
//声明树形组件的data
let treeData = ref([])
//树形组件的加载动画
let treeLoading = ref(false);
//获取权限树的方法

let getAllPermission = async () => {
    treeLoading.value = true;
    try {

        let res = await api.getAllPermissionApi()
        // console.log(res)
        //当前登入的角色,在展示权限的时候,如果当前角色没有对应的权限,那么这条权限数据要显示禁选状态

        //通过当前登入角色拥有的权限和所有的权限进行对比,如果当前角色拥有的权限中没有这条权限,那么这条权限就是禁选状态

        //将树形数据转换成扁平数据
        let flatData = (data = []) => {
            //扁平化处理后的数据
            let flatArr = []
            //递归函数
            let recursion = (arr = []) => {
                arr.forEach(item => {
                    //声明一个对象,用来存储扁平化处理后的数据
                    let obj = {
                        "_id": item._id,
                        "id": item.id,
                        "path": item.path,
                        "desc": item.desc,
                        "method": item.method,
                        "parentid": item.parentid,
                        "permissions": item.permissions
                    }

                    //如果item有children

                    if (item.children && item.children.length > 0) {
                        //递归调用
                        recursion(item.children)
                    }
                    flatArr.push(obj)
                })
            }
            recursion(data)
            return flatArr;
        }
        //获取所有的权限扁平化之后的数据
        let allPermissDataFlat = flatData(res.permissionPaths)
        //获取当前角色扁平化之后的数据
        let currentPermissionFlat = userStore.currentRolePermission.map(item => item.id)
        // console.log('----',currentPermissionFlat)
        //和当前角色拥有的权限进行对比

        // 判断当前角色拥有的权限数据中,是否包含了所有权限数据中的某一条
        let newData = allPermissDataFlat.map(item => {
            //如果有一条数据不包含,那么就要将这条数据添加上disabled:true
            if (!currentPermissionFlat.includes(item.id)) {
                // console.log(item)
                item.disabled = true
            }
            return item;
        })
        // console.log(newData)
        // 扁平数据不能直接给tree组件使用,所以需要再次转换成树形数据
        let flatToTree = (data = []) => {

            let tree = []

            data.forEach(item => {

                //先看看自己有没有parentid

                if (!item.parentid) {
                    //没有parentid,说明是根节点
                    tree.push(item)
                } else {

                    //通过parentid找到自己的父亲
                    let parent = data.find(v => v.id === item.parentid)
                    if (parent) {
                        //说明找到了父亲
                        if (!parent.children) {
                            parent.children = []
                        }
                        parent.children.push(item)
                    }
                }

            })

            return tree;
        }
        //赋值给el-tree组件
        treeData.value = flatToTree(newData)
        //关闭加载动画
        treeLoading.value = false;
    } catch (e) { console.log(e) }
}

//点击分配权限按钮

let grantPermission = (row) => {
    // console.log(row)
    //将当前点击的角色的roleid赋值给currentRoleid
    currentRoleid.value = row.roleid;
    nextTick(async () => {
        try {
            //获取点击的角色拥有的权限
            let res = await api.getCurrentRolePermissionApi({ roleid: row.roleid, type: 1 });
            //将当前角色的id全部映射到一个数组中
            let checkedKeys = res.data.map(item => item.id)
            // console.log(checkedKeys)
            tree.value.setCheckedKeys(checkedKeys)
        } catch (e) { }
    })

    //控制抽屉打开  
    showDrawer.value = true;
    //让点击的目标角色已经拥有的权限显示为勾选状态;
    //先获取点击的目标角色拥有的权限是什么
}

//抽屉关闭的时候

let handleDrawerClose = () => {
    showDrawer.value = false;
}

//抽屉打开的时候
let handleDrawerOpen = () => {
    //获取所有的权限数据
    getAllPermission()
}

//当前点击分配角色的id
let currentRoleid = ref("")

//点击保存按钮分配权限的时候

let savePermission = async () => {
    // console.log(tree.value.getCheckedKeys())
    let roleids = [currentRoleid.value]
    //获取tree中所有被选中的节点id
    let permission_ids = tree.value.getCheckedKeys()
    try {
        let res = await api.grantRoleApi({ roleids, permission_ids });
        // console.log(res)
        //关闭抽屉
        showDrawer.value = false;
    } catch (e) {
        console.log(e)
        showDrawer.value = false;
    }
}
//切换角色状态
//switch的loading状态
let switchLoading = ref(false)
//因为el-switch这个组件有Bug,会在加载页面的时候触发一次change事件,所以我们需要通过开关来限制它;
let switchChangeNum = 0;

//粗暴的解决方式
// setTimeout(() => {
//     switchFlag = true;
// }, 500)

//通过计数的方式解决
let changeStatus = async (row) => {

    // console.log(row.roleid)
    // console.log(row.status)
    switchChangeNum++;
    //开关关闭不要往下执行
    if (switchChangeNum <= 1) {
        return;
    }
    try {
        switchLoading.value = true;
        let res = await api.updateRoleApi({ roleid: row.roleid, status: row.status })
        switchLoading.value = false;
    } catch (e) {
        //没有权限或者出错了,重新请求列表()
        getAllRole()
        console.log(e)
        switchLoading.value = false;
    }
}

//调用方法获取数据

onMounted(() => {
    getAllRole()
})



</script>

<script>
export default {
    //自己定义的属性
    meta: {
        key: "角色管理",
        icon: "icon-jiaoseguanli"
    }
}
</script>